import { createSlice } from '@reduxjs/toolkit'

const tabSlice = createSlice({
  name: 'tab',
  initialState: {
    isCollapse: false,
    tabList: [
      {
        path: '/home',
        name: 'home',
        label: '首页'
      },
    ],
  },
  reducers: {
    collapseMenu: state => { state.isCollapse = !state.isCollapse },

    updataMenuList: (state, { payload:val})  => {
      if(val.name !== 'home') {
        // findIndex方法返回数组中满足条件的第一个元素的索引，如果没有找到则返回-1
        const result = state.tabList.findIndex(item => item.name === val.name)
        if(result === -1) {
          state.tabList.push(val)
        }
      }
    },

    closeTab: (state, {payload: val}) => {
      const index = state.tabList.findIndex(item => item.name === val.name)
      if(index !== -1) {
        state.tabList.splice(index, 1)    //index：要删除标签的索引，第二参数：删除数量
      }
    },
    closeAllTab: state => { 
      const homeTab = state.tabList.find(tab => tab.name === 'home')
      state.tabList = homeTab ? [homeTab] : []
    }
  }
})

export const { collapseMenu, updataMenuList, closeTab, closeAllTab } = tabSlice.actions
export default tabSlice.reducer